"use client"

import { useState, useEffect } from "react"
import { View, Text, TouchableOpacity, StyleSheet, SafeAreaView, ScrollView } from "react-native"

interface TrainingScreenProps {
  onBack: () => void
}

export default function TrainingScreen({ onBack }: TrainingScreenProps) {
  const [isTraining, setIsTraining] = useState(false)
  const [currentRound, setCurrentRound] = useState(1)
  const [totalRounds] = useState(10)
  const [score, setScore] = useState(0)
  const [reactionTime, setReactionTime] = useState(245)
  const [timeLeft, setTimeLeft] = useState(300)
  const [activeLED, setActiveLED] = useState<number | null>(null)
  const [sequence, setSequence] = useState<number[]>([])
  const [userSequence, setUserSequence] = useState<number[]>([])
  const [gamePhase, setGamePhase] = useState<"waiting" | "showing" | "input" | "result">("waiting")

  const ledPositions = [
    { id: 1, row: 0, col: 2 },
    { id: 2, row: 0, col: 3 },
    { id: 3, row: 1, col: 4 },
    { id: 4, row: 2, col: 4 },
    { id: 5, row: 3, col: 3 },
    { id: 6, row: 3, col: 2 },
    { id: 7, row: 2, col: 1 },
    { id: 8, row: 1, col: 1 },
  ]

  useEffect(() => {
    let interval: NodeJS.Timeout
    if (isTraining && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft((prev) => prev - 1)
      }, 1000)
    }
    return () => clearInterval(interval)
  }, [isTraining, timeLeft])

  const startTraining = () => {
    setIsTraining(true)
    setGamePhase("showing")
    generateSequence()
  }

  const pauseTraining = () => {
    setIsTraining(false)
  }

  const stopTraining = () => {
    setIsTraining(false)
    setCurrentRound(1)
    setScore(0)
    setGamePhase("waiting")
    setActiveLED(null)
    setSequence([])
    setUserSequence([])
  }

  const generateSequence = () => {
    const newSequence = Array.from(
      { length: Math.min(3 + Math.floor(currentRound / 2), 8) },
      () => Math.floor(Math.random() * 8) + 1,
    )
    setSequence(newSequence)
    setUserSequence([])
    showSequence(newSequence)
  }

  const showSequence = async (seq: number[]) => {
    setGamePhase("showing")
    for (let i = 0; i < seq.length; i++) {
      await new Promise((resolve) => setTimeout(resolve, 500))
      setActiveLED(seq[i])
      await new Promise((resolve) => setTimeout(resolve, 800))
      setActiveLED(null)
      await new Promise((resolve) => setTimeout(resolve, 200))
    }
    setGamePhase("input")
  }

  const handleLEDPress = (ledId: number) => {
    if (gamePhase !== "input") return

    const newUserSequence = [...userSequence, ledId]
    setUserSequence(newUserSequence)

    if (newUserSequence[newUserSequence.length - 1] !== sequence[newUserSequence.length - 1]) {
      setGamePhase("result")
      setTimeout(() => nextRound(), 1500)
      return
    }

    if (newUserSequence.length === sequence.length) {
      setScore((prev) => prev + 10 * currentRound)
      setGamePhase("result")
      setTimeout(() => nextRound(), 1500)
    }
  }

  const nextRound = () => {
    if (currentRound < totalRounds) {
      setCurrentRound((prev) => prev + 1)
      generateSequence()
    } else {
      stopTraining()
    }
  }

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins}:${secs.toString().padStart(2, "0")}`
  }

  const renderLEDGrid = () => {
    const grid = Array(5)
      .fill(null)
      .map(() => Array(6).fill(null))

    ledPositions.forEach((led) => {
      grid[led.row][led.col] = led
    })

    return grid.map((row, rowIndex) => (
      <View key={rowIndex} style={styles.gridRow}>
        {row.map((cell, colIndex) => {
          if (cell) {
            const isActive = activeLED === cell.id
            return (
              <TouchableOpacity
                key={`${rowIndex}-${colIndex}`}
                style={[
                  styles.ledButton,
                  isActive && styles.ledButtonActive,
                  gamePhase !== "input" && styles.ledButtonDisabled,
                ]}
                onPress={() => handleLEDPress(cell.id)}
                disabled={gamePhase !== "input"}
              >
                <Text style={[styles.ledButtonText, isActive && styles.ledButtonTextActive]}>{cell.id}</Text>
              </TouchableOpacity>
            )
          } else {
            return <View key={`${rowIndex}-${colIndex}`} style={styles.gridEmpty} />
          }
        })}
      </View>
    ))
  }

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* Header */}
        <View style={styles.header}>
          <View style={styles.headerContent}>
            <View style={styles.headerLeft}>
              <TouchableOpacity style={styles.backButton} onPress={onBack}>
                <Text style={styles.backButtonText}>← 返回</Text>
              </TouchableOpacity>
              <Text style={styles.headerTitle}>SEQUENCE TRAINING</Text>
            </View>
            <View style={styles.headerRight}>
              <Text style={styles.headerInfo}>
                第 {currentRound}/{totalRounds} 轮
              </Text>
              <Text style={styles.headerInfo}>⏱ {formatTime(timeLeft)}</Text>
              <View style={styles.headerButtons}>
                {!isTraining ? (
                  <TouchableOpacity style={styles.startButton} onPress={startTraining}>
                    <Text style={styles.startButtonText}>▶ 开始</Text>
                  </TouchableOpacity>
                ) : (
                  <>
                    <TouchableOpacity style={styles.pauseButton} onPress={pauseTraining}>
                      <Text style={styles.pauseButtonText}>⏸</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.stopButton} onPress={stopTraining}>
                      <Text style={styles.stopButtonText}>⏹</Text>
                    </TouchableOpacity>
                  </>
                )}
              </View>
            </View>
          </View>
          <View style={styles.headerBorder} />
        </View>

        <View style={styles.mainContent}>
          {/* Stats Section */}
          <View style={styles.statsSection}>
            <Text style={styles.sectionTitle}>训练数据</Text>
            <View style={styles.statsGrid}>
              <View style={styles.statCard}>
                <Text style={styles.statValue}>{score}</Text>
                <Text style={styles.statLabel}>总分</Text>
              </View>
              <View style={styles.statCard}>
                <Text style={styles.statValue}>{reactionTime}</Text>
                <Text style={styles.statLabel}>反应时间 (ms)</Text>
              </View>
              <View style={styles.statCard}>
                <Text style={styles.statValue}>{Math.round((score / (currentRound * 10)) * 100) || 0}%</Text>
                <Text style={styles.statLabel}>准确率</Text>
              </View>
            </View>
          </View>

          {/* Training Area */}
          <View style={styles.trainingSection}>
            <View style={styles.titleSection}>
              <Text style={styles.mainTitle}>SEQUENCE_{"\n"}MEMORY</Text>
              <Text style={styles.subtitle}>
                {gamePhase === "waiting" && "点击开始按钮开始训练"}
                {gamePhase === "showing" && "请记住LED亮起的顺序"}
                {gamePhase === "input" && "按照刚才的顺序点击LED"}
                {gamePhase === "result" && (userSequence.length === sequence.length ? "正确！" : "错误，继续加油！")}
              </Text>
            </View>

            {/* LED Grid */}
            <View style={styles.ledContainer}>
              <View style={styles.ledGrid}>{renderLEDGrid()}</View>
            </View>

            {/* Sequence Display */}
            {sequence.length > 0 && (
              <View style={styles.sequenceDisplay}>
                <Text style={styles.sequenceTitle}>
                  {gamePhase === "showing"
                    ? "正在显示序列..."
                    : gamePhase === "input"
                      ? `请输入 ${sequence.length} 个LED的顺序`
                      : "序列完成"}
                </Text>
                <View style={styles.sequenceItems}>
                  {sequence.map((ledId, index) => (
                    <View
                      key={index}
                      style={[
                        styles.sequenceItem,
                        index < userSequence.length
                          ? userSequence[index] === ledId
                            ? styles.sequenceItemCorrect
                            : styles.sequenceItemWrong
                          : styles.sequenceItemPending,
                      ]}
                    >
                      <Text
                        style={[styles.sequenceItemText, index < userSequence.length && styles.sequenceItemTextActive]}
                      >
                        {ledId}
                      </Text>
                    </View>
                  ))}
                </View>
              </View>
            )}
          </View>

          {/* Progress Section */}
          <View style={styles.progressSection}>
            <View style={styles.progressCard}>
              <View style={styles.progressHeader}>
                <Text style={styles.progressTitle}>训练进度</Text>
                <View style={styles.orangeDot} />
              </View>
              <Text style={styles.progressValue}>{Math.round((currentRound / totalRounds) * 100)}%</Text>
              <Text style={styles.progressLabel}>完成度</Text>
              <View style={styles.progressBar}>
                <View style={[styles.progressFill, { width: `${(currentRound / totalRounds) * 100}%` }]} />
              </View>
            </View>
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffffff",
  },
  scrollContent: {
    flexGrow: 1,
    padding: 32,
  },
  header: {
    marginBottom: 48,
  },
  headerContent: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingBottom: 24,
  },
  headerLeft: {
    flexDirection: "row",
    alignItems: "center",
    gap: 16,
  },
  backButton: {
    backgroundColor: "transparent",
    borderWidth: 1,
    borderColor: "#e5e7eb",
    height: 32,
    paddingHorizontal: 16,
    justifyContent: "center",
    alignItems: "center",
  },
  backButtonText: {
    fontSize: 14,
    color: "#666666",
  },
  headerTitle: {
    fontSize: 14,
    fontWeight: "500",
    color: "#000000",
  },
  headerRight: {
    flexDirection: "row",
    alignItems: "center",
    gap: 24,
  },
  headerInfo: {
    fontSize: 14,
    color: "#666666",
  },
  headerButtons: {
    flexDirection: "row",
    gap: 8,
  },
  startButton: {
    backgroundColor: "#22c55e",
    height: 32,
    paddingHorizontal: 16,
    justifyContent: "center",
    alignItems: "center",
  },
  startButtonText: {
    fontSize: 14,
    fontWeight: "500",
    color: "#ffffff",
  },
  pauseButton: {
    backgroundColor: "transparent",
    borderWidth: 1,
    borderColor: "#e5e7eb",
    height: 32,
    paddingHorizontal: 16,
    justifyContent: "center",
    alignItems: "center",
  },
  pauseButtonText: {
    fontSize: 14,
    color: "#666666",
  },
  stopButton: {
    backgroundColor: "#ef4444",
    height: 32,
    paddingHorizontal: 16,
    justifyContent: "center",
    alignItems: "center",
  },
  stopButtonText: {
    fontSize: 14,
    fontWeight: "500",
    color: "#ffffff",
  },
  headerBorder: {
    height: 1,
    backgroundColor: "#e5e7eb",
  },
  mainContent: {
    flex: 1,
    // 强制垂直布局
    flexDirection: "column",
    gap: 24,
  },
  leftStats: {
    flex: 1,
    paddingRight: 32,
    borderRightWidth: 1,
    borderRightColor: "#e5e7eb",
    gap: 24,
  },
  statCard: {
    borderWidth: 1,
    borderColor: "#e5e7eb",
    padding: 8,
    flex: 1,
    alignItems: "center",
  },
  statValue: {
    fontSize: 32,
    fontWeight: "bold",
    color: "#000000",
    marginBottom: 8,
  },
  statLabel: {
    fontSize: 14,
    color: "#666666",
  },
  trainingArea: {
    flex: 2,
  },
  titleSection: {
    marginBottom: 32,
  },
  mainTitle: {
    fontSize: 32,
    fontWeight: "bold",
    color: "#000000",
    lineHeight: 40,
    marginBottom: 16,
  },
  subtitle: {
    fontSize: 16,
    color: "#666666",
  },
  ledContainer: {
    borderWidth: 1,
    borderColor: "#e5e7eb",
    padding: 16,
    marginBottom: 32,
    alignItems: "center",
  },
  ledGrid: {
    alignItems: "center",
    justifyContent: "center",
  },
  gridRow: {
    flexDirection: "row",
    gap: 8,
    marginBottom: 8,
  },
  ledButton: {
    width: 48,
    height: 48,
    borderWidth: 2,
    borderColor: "#e5e7eb",
    backgroundColor: "#ffffff",
    justifyContent: "center",
    alignItems: "center",
  },
  ledButtonActive: {
    backgroundColor: "#f97316",
    borderColor: "#f97316",
  },
  ledButtonDisabled: {
    opacity: 0.6,
  },
  ledButtonText: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#374151",
  },
  ledButtonTextActive: {
    color: "#ffffff",
  },
  gridEmpty: {
    width: 48,
    height: 48,
    backgroundColor: "#f3f4f6",
  },
  sequenceDisplay: {
    alignItems: "center",
  },
  sequenceTitle: {
    fontSize: 14,
    color: "#666666",
    marginBottom: 16,
  },
  sequenceItems: {
    flexDirection: "row",
    gap: 8,
  },
  sequenceItem: {
    width: 32,
    height: 32,
    borderWidth: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  sequenceItemPending: {
    backgroundColor: "#ffffff",
    borderColor: "#e5e7eb",
  },
  sequenceItemCorrect: {
    backgroundColor: "#22c55e",
    borderColor: "#22c55e",
  },
  sequenceItemWrong: {
    backgroundColor: "#ef4444",
    borderColor: "#ef4444",
  },
  sequenceItemText: {
    fontSize: 14,
    fontWeight: "bold",
    color: "#666666",
  },
  sequenceItemTextActive: {
    color: "#ffffff",
  },
  rightProgress: {
    flex: 1,
    paddingLeft: 32,
    borderLeftWidth: 1,
    borderLeftColor: "#e5e7eb",
  },
  progressCard: {
    borderWidth: 1,
    borderColor: "#e5e7eb",
    padding: 24,
  },
  progressHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 16,
  },
  progressTitle: {
    fontSize: 14,
    fontWeight: "500",
    color: "#000000",
  },
  orangeDot: {
    width: 12,
    height: 12,
    backgroundColor: "#f97316",
    borderRadius: 6,
  },
  progressValue: {
    fontSize: 32,
    fontWeight: "bold",
    color: "#000000",
    marginBottom: 8,
  },
  progressLabel: {
    fontSize: 14,
    color: "#666666",
    marginBottom: 16,
  },
  progressBar: {
    height: 8,
    backgroundColor: "#f3f4f6",
  },
  progressFill: {
    height: 8,
    backgroundColor: "#f97316",
  },
  statsSection: {
    paddingHorizontal: 16,
    marginBottom: 32,
  },

  statsGrid: {
    flexDirection: "row",
    gap: 12,
    justifyContent: "space-between",
  },

  trainingSection: {
    paddingHorizontal: 16,
    marginBottom: 32,
    flex: 1,
  },

  progressSection: {
    paddingHorizontal: 16,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: "#000000",
    marginBottom: 16,
  },
})
